import { Disposable, InjectionToken, container } from 'tsyringe'
import { ROBOT_APP_PAGE, RobotAppPage } from './page';
import { Context } from './context';
import { FloatyWindow } from '../autox/floatWindow';

export const ROBOT_APP: InjectionToken<RobotApp> = `ROBOT_APP`;
export const createRobotApp = (name: string, title?: string) => () => new RobotApp(name, title)
export const createRobotSystemApp = (name: string, title?: string) => () => new RobotApp(name, title, true)

export class RobotApp implements Disposable {
    private packageName: string;
    private pages: RobotAppPage[];
    private isRunning: boolean = true;
    private isSystem: boolean = false;
    public title: string = ``
    ctx: Context;
    constructor(packageName: string, title: string = ``, isSystem: boolean = false) {
        this.packageName = packageName;
        const pages = container.resolveAll(ROBOT_APP_PAGE);
        this.pages = pages.filter(page => page.is(this.packageName))
        this.ctx = container.resolve(Context)
        this.title = title;
        this.isSystem = isSystem;
    }
    getIsSystem(): boolean {
        return this.isSystem;
    }
    /**
     * 外部获取包名
     * @returns string
     */
    getPackageName() {
        return this.packageName;
    }
    /**
     * 当activity触发
     * @param activity string
     */
    prev: RobotAppPage;
    onActivity(activity: string, latestPackage: string) {
        const page = this.pages.find(page => page.accept(activity))
        this.ctx.setCurrentPage(page, latestPackage)
    }
    /**
     * 退出应用
     */
    dispose(): void {
        this.close()
    }
    /**
     * @param timeout 单位是秒
     * @returns boolean APP是否打开成功
     */
    open() {
        if (this.isRunning) return false;
        this.isRunning = true;
    }
    /**
     * 关闭APP
     */
    close() {
        if (!this.isRunning) return false;
        this.isRunning = false;
        this.prev?.out();
    }
}
